import os
from pathlib import Path

from django.templatetags.static import static

# 项目路径配置
# Path(__file__).resolve().parent 表示当前 settings.py 所在目录
PROJECT_DIR = Path(__file__).resolve().parent
# BASE_DIR 表示项目根目录（通常包含 manage.py）
BASE_DIR = PROJECT_DIR.parent
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#std-setting-BASE_DIR


# 安全密钥，用于加密 session、签名等
SECRET_KEY = "django-insecure-s_&u)4#*u$r-zya74m+yjy$fa2tgq43p(%#ny#pec-xiqtbh%d"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#secret-key

# 调试模式，True 表示开启（仅开发环境使用）
DEBUG = True
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#debug

# 允许访问的主机名（生产环境必须配置）
ALLOWED_HOSTS = []
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#allowed-hosts


# 自定义用户模型，替代 Django 默认 User
AUTH_USER_MODEL = "identify.User"
# https://docs.djangoproject.com/zh-hans/5.2/topics/auth/customizing/#substituting-a-custom-user-model


# 已安装的应用（按加载顺序）
INSTALLED_APPS = [
    "identify",  # 用户模块
    "notebook",  # 笔记模块
    "unfold",  # 第三方后台美化（必须在 admin 前）
    "django.contrib.admin",  # 管理后台
    "django.contrib.auth",  # 用户认证
    "django.contrib.contenttypes",  # 内容类型框架
    "django.contrib.sessions",  # 会话框架
    "django.contrib.messages",  # 消息框架
    "django.contrib.staticfiles",  # 静态文件管理
]
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#installed-apps


# 中间件（请求/响应处理顺序）
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",  # 安全相关
    "django.contrib.sessions.middleware.SessionMiddleware",  # Session 支持
    "django.middleware.common.CommonMiddleware",  # 常用功能
    "django.middleware.locale.LocaleMiddleware",  # 国际化/多语言
    "django.middleware.csrf.CsrfViewMiddleware",  # CSRF 防护
    "django.contrib.auth.middleware.AuthenticationMiddleware",  # 用户认证
    "django.contrib.messages.middleware.MessageMiddleware",  # 消息提示
    "django.middleware.clickjacking.XFrameOptionsMiddleware",  # 防止点击劫持
]
# https://docs.djangoproject.com/zh-hans/5.2/ref/middleware/


# URL 配置文件入口
ROOT_URLCONF = "core.urls"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#root-urlconf


# 模板配置
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",  # 模板引擎
        "DIRS": [BASE_DIR / "templates"],  # 额外模板目录
        "APP_DIRS": True,  # 自动查找各 app 下的 templates 目录
        "OPTIONS": {
            "context_processors": [  # 模板上下文处理器
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "core.context.get_notebook_count",  # 自定义上下文处理器，显示笔记总数
            ],
        },
    },
]
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#templates


# WSGI 入口
WSGI_APPLICATION = "core.wsgi.application"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#wsgi-application


# 数据库配置（默认 SQLite）
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",  # 数据库引擎
        "NAME": BASE_DIR / "db.sqlite3",  # 数据库文件路径
    }
}
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#databases


# 密码验证器（这里仅使用最小长度，放宽要求）
AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
        "OPTIONS": {
            "min_length": 4,
        },
    },
]
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#auth-password-validators


# 语言设置
LANGUAGE_CODE = "zh-hans"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#language-code

# 时区设置
TIME_ZONE = "Asia/Shanghai"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#time-zone

# 是否启用国际化
USE_I18N = True
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#use-i18n

# 是否使用时区（True → 存储为 UTC）
USE_TZ = True
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#use-tz


# 静态文件配置
STATIC_URL = "/static/"  # URL 前缀
STATICFILES_DIRS = [
    BASE_DIR / "static",  # 项目内静态文件目录
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")  # 收集静态文件的目标目录
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#static-url


# 媒体文件配置（用户上传）
MEDIA_URL = "/uploads/"  # URL 前缀
MEDIA_ROOT = os.path.join(BASE_DIR, "uploads")  # 存储目录
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#media-root


# 默认主键类型（大整型自增）
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#default-auto-field


# 国际化翻译文件存放路径
LOCALE_PATHS = [
    os.path.join(BASE_DIR, "locale"),
]
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#locale-paths


# unfold 插件配置（第三方后台美化）
UNFOLD = {
    "SITE_TITLE": "ImQi1云笔记管理系统",  # 浏览器标签上的标题
    "SITE_HEADER": "ImQi1云笔记",  # 后台页面顶部标题
    "SITE_SUBHEADER": "让记录笔记更快捷 ",  # 子标题
    "SITE_FAVICONS": [  # 网页 favicon 图标
        {
            "rel": "icon",
            "sizes": "32x32",
            "type": "image/svg+xml",
            "href": lambda _: static("icon/paper.svg"),
        },
    ],
    "SITE_ICON": lambda _: static("icon/paper.svg"),  # 后台左上角图标
}
# 文档（第三方包 unfold）：https://github.com/unfoldadmin/django-unfold

# 日志
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'color': {
            '()': 'colorlog.ColoredFormatter',   # 指定使用彩色格式化器
            'format': '[%(log_color)s%(asctime)s%(reset)s] '
                      '%(log_color)s%(levelname)-8s%(reset)s '
                      '%(blue)s%(name)s:%(lineno)s%(reset)s '
                      '%(message_log_color)s%(message)s',
            'log_colors': {
                'DEBUG':    'cyan',
                'INFO':     'green',
                'WARNING':  'yellow',
                'ERROR':    'red',
                'CRITICAL': 'bold_red',
            },
            'secondary_log_colors': {
                'message': {
                    'ERROR': 'red',
                    'CRITICAL': 'bold_red',
                }
            },
            'style': '%',
        },
        'verbose': {  # 文件还是纯文本
            'format': '[{asctime}] {levelname} {name} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'color',
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'django.log',
            'formatter': 'verbose',
            'encoding': 'utf-8',
        },
    },
    'root': {   # 所有 logger 默认走 root
        'handlers': ['console', 'file'],
        'level': 'DEBUG',
    },
    'loggers': {
        'django.request': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['console', 'file'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}
# https://docs.djangoproject.com/zh-hans/5.2/ref/settings/#logging
